import React, { ElementRef, memo, useEffect, useRef } from 'react'
import type { FC, ReactNode } from 'react'
import { Carousel } from 'antd'

import { NewAlbumWrapper } from './style'
import AreaHeader from '@/components/area-header'
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { fetchDiscoverNewAlbum } from '@/store/modules/discover'
import NewAlbumItem from '@/components/new-album-item'

interface IProps {
  children?: ReactNode
}

const NewAlbum: FC<IProps> = () => {
  const dispatch = useAppDispatch()

  // 获取新碟上架数据
  useEffect(() => {
    dispatch(fetchDiscoverNewAlbum())
  }, [])

  const { newAlbum } = useAppSelector((state) => {
    return {
      newAlbum: state.discover.newAlbum
    }
  }, shallowEqualApp)

  const carouselRef = useRef<ElementRef<typeof Carousel>>(null)

  const changeHandle = (type: string) => {
    type === 'prev' ? carouselRef.current?.prev() : carouselRef.current?.next()
  }

  return (
    <NewAlbumWrapper>
      {/* 头部 */}
      <AreaHeader
        title="新碟上架"
        moreText="更多"
        moreLink="/discover/album"
      ></AreaHeader>
      {/* 内容 */}
      <div className='content'>
        <Carousel className="carousel" dots={false} ref={carouselRef} speed={1000}>
          <ul className="carousel_item">
            {newAlbum?.slice(0, 5).map((item) => {
              return <NewAlbumItem item={item} key={item.id}></NewAlbumItem>
            })}
          </ul>
          <ul className="carousel_item">
            {newAlbum?.slice(5, 10).map((item) => {
              return <NewAlbumItem item={item} key={item.id}></NewAlbumItem>
            })}
          </ul>
        </Carousel>
        <a className="btn prev sprite_02" onClick={() => changeHandle('prev')}></a>
        <a className="btn next sprite_02" onClick={() => changeHandle('prev')}></a>
      </div>
    </NewAlbumWrapper>
  )
}

export default memo(NewAlbum)
